package com.lishe.lishe.lishe.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.os.Handler;
import android.support.multidex.MultiDex;
import android.view.Gravity;
import android.view.View;

import com.lishe.lishe.R;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.widget.ClassicsFooter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;

import java.util.Stack;

import cn.jpush.android.api.JPushInterface;


/**
 * Created by law on 2017/8/11.
 */

public class BaseApplication extends Application {
    private static String TAG = BaseApplication.class.getSimpleName();
    /*Activity堆*/
    private Stack<Activity> activityStack = new Stack<Activity>();
    private static BaseApplication baseApplication;
    private static Context context;
    public boolean showUpdateDialog=true;

    //static 代码段可以防止内存泄露,smartrefreshlayout
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
            @SuppressLint("ResourceAsColor")
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
//                layout.setPrimaryColorsId(R.color.white, R.color.gray_6);//全局设置主题颜色
//                BezierCircleHeader header = new BezierCircleHeader(context);
                ClassicsHeader.REFRESH_HEADER_PULLDOWN = "下拉刷新福利";
                ClassicsHeader.REFRESH_HEADER_REFRESHING = "刷新中...";
                ClassicsHeader.REFRESH_HEADER_RELEASE = "松开刷新福利";
//                RefreshHeaderLayout0 header=new RefreshHeaderLayout0(context);
//                MaterialHeader header=new MaterialHeader(context);
                ClassicsHeader header = new ClassicsHeader(context);
                header.setGravity(Gravity.CENTER);
                header.setTextSizeTitle(12);//设置标题文字大小（sp单位）
                header.setDrawableMarginRight(5);//设置图片和箭头和文字的间距（dp单位）
                header.setEnableLastTime(false);
                header.setFinishDuration(0);
                header.getLastUpdateText().setVisibility(View.GONE);
                header.setArrowDrawable(context.getResources().getDrawable(R.mipmap.down));
                header.setDrawableArrowSize(13);//设置箭头的大小（dp单位）
                header.setProgressDrawable(context.getResources().getDrawable(R.mipmap.refresh));
                header.setDrawableProgressSize(13);//设置图片的大小（dp单位）
                header.setSpinnerStyle(SpinnerStyle.Translate);
                return header;//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
//                layout.setPrimaryColorsId(R.color.color4138,R.color.white);
                ClassicsFooter.REFRESH_FOOTER_LOADING = "正在加载商品";//"正在加载...";
                ClassicsFooter.REFRESH_FOOTER_FINISH = "加载完成";
                ClassicsFooter.REFRESH_FOOTER_ALLLOADED = "已经到底啦~";
                ClassicsFooter footer = new ClassicsFooter(context);
                footer.setProgressDrawable(context.getResources().getDrawable(R.mipmap.refresh));
                footer.setDrawableMarginRight(5);//设置图片和箭头和文字的间距（dp单位）
                footer.setTextSizeTitle(12);//设置标题文字大小（sp单位）
                footer.setDrawableProgressSize(13);//设置图片的大小（dp单位）
                footer.setSpinnerStyle(SpinnerStyle.Translate);
                footer.setFinishDuration(250);
                footer.setGravity(Gravity.CENTER);
                return footer;
            }
        });
    }

    private Handler mMainThreadHandler;

    @Override
    public void onCreate() {
        super.onCreate();
        //极光推送.暂时不开放
//        JPushInterface.setDebugMode(true);
//        JPushInterface.init(this);
        //图片imageLoader
//        ImageLoaderConfiguration();
        CrashReport.initCrashReport(getApplicationContext(), "0289c0ded7", Globals.DEBUG);

        initTypefaces(this);
        context = getApplicationContext();
        mMainThreadHandler = new android.os.Handler();
        PlatformConfig.setWeixin(Globals.WeiXin_appId, Globals.WeiXin_secret);
        PlatformConfig.setQQZone(Globals.QQ_appId, Globals.QQ_appKey);
        UMShareAPI.get(this);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }

    public void addActivity(final Activity curAT) {
        if (null == activityStack) {
            activityStack = new Stack<Activity>();
        }
        if (!activityStack.contains(curAT)) {
            activityStack.add(curAT);
        }
    }

    public void removeActivity(final Activity curAT) {
        if (null == activityStack) {
            activityStack = new Stack<Activity>();
        }
        if (activityStack.contains(curAT)) {
            activityStack.remove(curAT);
        }
    }

    //获取最后一个Activity
    public Activity currentActivity() {
        Activity activity = activityStack.lastElement();
        return activity;
    }


    public static Context getContext() {
        return context;
    }

    //返回寨内Activity的总数
    public int howManyActivities() {
        return activityStack.size();
    }

    //关闭所有Activity
    public void finishAllActivities() {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
    }

    /**
     * 获取BaseApplication实例
     *
     * @return
     */
    public static BaseApplication getInstace() {
        if (baseApplication == null) {
            baseApplication = new BaseApplication();
        }
        return baseApplication;
    }
//
//    /**
//     * imageload初始化
//     */
//    private void ImageLoaderConfiguration() {
//        //通过StorageUtils获取内置的内存目录/data/data/.../cache
//        File cacheDir = StorageUtils.getCacheDirectory(this);
//
//        ImageLoaderConfiguration config = new ImageLoaderConfiguration
//                .Builder(getApplicationContext())
//                .memoryCacheExtraOptions(480, 800) //即保存的每个缓存文件的最大长宽
//                .threadPoolSize(3) //线程池内加载的数量
//                .threadPriority(Thread.NORM_PRIORITY - 2)
//                //解释：当同一个Uri获取不同大小的图片，缓存到内存时，只缓存一个。默认会缓存多个不同的大小的相同图片
//                .denyCacheImageMultipleSizesInMemory() //拒绝缓存多个图片。
//                .memoryCache(new WeakMemoryCache()) //缓存策略你可以通过自己的内存缓存实现 ，这里用弱引用，缺点是太容易被回收了，不是很好！
//                .memoryCacheSize(2 * 1024 * 1024) //设置内存缓存的大小
//                .diskCacheSize(60 * 1024 * 1024) //设置磁盘缓存大小 60M
//                .diskCacheFileNameGenerator(new Md5FileNameGenerator()) //将保存的时候的URI名称用MD5 加密
//                .tasksProcessingOrder(QueueProcessingType.LIFO) //设置图片下载和显示的工作队列排序
//                .diskCacheFileCount(100) //缓存的文件数量
//                .diskCache(new UnlimitedDiskCache(cacheDir)) //自定义缓存路径
////                .defaultDisplayImageOptions(defaultOptions) //显示图片的参数，默认： DisplayImageOptions.createSimple()
//                .imageDownloader(new BaseImageDownloader(this, 5 * 1000, 30 * 1000)) // connectTimeout(5s), readTimeout(30s) 超时时间
//                .writeDebugLogs() //打开调试日志
//                .build();//开始构建
//        //配置使用
//        ImageLoader.getInstance().init(config);
//    }

    private static Typeface TypeFaceRegular;

    private static Typeface TypeFaceMedium;

    private static void initTypefaces(Context context) {
        AssetManager mgr = context.getAssets();
        TypeFaceRegular = Typeface.createFromAsset(mgr, "fonts/PingFang_SC_Regular.ttf");
        TypeFaceMedium = Typeface.createFromAsset(mgr, "fonts/PingFang-Medium.ttf");
    }

    public static Typeface getTypefaceRegular() {
        return TypeFaceRegular;
    }

    public static Typeface getTypeFaceMedium() {
        return TypeFaceMedium;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        //解决minSdkVersion 在小于20的情况分包导致ClassNotFound 问题
        MultiDex.install(base);
    }

    public Handler getmMainThreadHandler() {
        return mMainThreadHandler;
    }
}
